#!/usr/bin/python




import re
import cgi
import time
import random
import os
import words

#from __future__ import generators

from google.appengine.ext import webapp
from google.appengine.ext import db

from google.appengine.api import users
from google.appengine.api import images

from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


def delete_cookie(handler,name):
	"""Lo que hace esto es setear el valor de la cookie en vacio
	y darle una fecha de expiracion en el pasado.
	Con esto se logra que se destruya la cookie. """

	handler.response.headers.add_header(
		'Set-Cookie',
		"%s=cookie_error; expires=%s" % (name, "Thu, 01-Jan-1980 00:00:00 GMT")
		)
	return

def create_cookie(handler,name,value):
	handler.response.headers.add_header(
					'Set-Cookie', 
					'%s=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' \
					% (name , value.encode())
					)
	return

def get_cookie(handler,name):
	if cookie_exists(handler,name):
		cookies = dict(handler.request.cookies)
		return cookies[name]
	else:
		return None

def cookie_exists(handler, name):
	cookies = dict(handler.request.cookies)
	return name in cookies



def has_only_letters(string):
	return re.match("^[A-Za-z]*$", string)


def xcombinations(items, n):
	if n==0: yield []
	else:
		for i in xrange(len(items)):
			for cc in xcombinations(items[:i]+items[i+1:],n-1):
				yield [items[i]]+cc

class Carreta():
	
	def __init__(self):
		self.contenido = []
	
c = Carreta()


class UserStore(db.Model):
	
	username = db.StringProperty(required = True)
	password = db.StringProperty(required = True)
	
	registration_date = db.DateTimeProperty(auto_now_add=True)
	
	mail = db.StringProperty()
	
	#birthdate = db.DateTimeProperty()
	#documento = db.StringProperty()
	#ciudad = db.StringProperty()
	
	avatar = db.BlobProperty()
	
class Visitor(db.Model):

        content = db.StringProperty(multiline=True)
        date = db.DateTimeProperty(auto_now_add=True)
        writer = db.StringProperty()
	avatar = db.BlobProperty()
	
class LogHistory(db.Model):
	
	user = db.StringProperty()
	ip = db.StringProperty()
	date = db.DateTimeProperty(auto_now_add=True)
	

class MainPage(webapp.RequestHandler):
	
	def get(self):
		ip = self.request.remote_addr
		self.response.out.write(template.render('templates/main.mako',{'ip':ip}))
		
class Register(webapp.RequestHandler):
	
	c.show_pwd_diff = False
	c.show_pwd_lenerr = False
	c.show_user_exists = False
	c.show_user_lenerr = False
	c.user_sugerencia = ''
	c.entered_username = ''

		
	def get(self):
		
		values = {'show_pwd_diff' : c.show_pwd_diff,
			'show_user_exists' : c.show_user_exists,
			'user_sugerencia' : c.user_sugerencia,
			'entered_username' : c.entered_username,
			'show_pwd_lenerr' : c.show_pwd_lenerr,
			'show_user_lenerr' : c.show_user_lenerr,
			}
		self.response.out.write(template.render('templates/register.mako',values))
		c.show_pwd_diff = False
		c.show_pwd_lenerr = False
		
	
	def post(self):
		
		error_flag = False
		c.show_user_exists = False
		
		entered_username = cgi.escape(self.request.get('username')).lower()
		
		
		c.entered_username = entered_username
		
		if(len(entered_username) > 30 or len(entered_username) < 4):
			error_flag = True
			c.show_user_lenerr = True
					
		pwd1 = self.request.get('password1')
		pwd2 = self.request.get('password2')
		
		if (pwd1 != pwd2):
			error_flag = True
			c.show_pwd_diff = True
		
		if ( not c.show_pwd_diff and (len(pwd1) < 6 or len(pwd1) > 30)):
			c.show_pwd_lenerr = True
			error_flag = True
		
		user_table = db.GqlQuery("SELECT * FROM UserStore")
		for old_user in user_table:
			if ( old_user.username == entered_username ):
				c.show_user_exists = True
				error_flag = True
				c.user_sugerencia = entered_username + str(int(random.random()*10)) + str(int(random.random()*10))
				break
		
		
			
		if ( error_flag is not True ):
			new_account = UserStore(username = entered_username, password = pwd1)
			new_account.put()
			c.show_pwd_diff = False
			c.show_user_exists = False
			c.show_user_lenerr = False
			c.user_sugerencia = ''
			c.entered_username = ''
			c.show_pwd_lenerr = False
			self.redirect('/correct')
		else:
			self.redirect('/register')	
			
class Correct(webapp.RequestHandler):
	
	def get(self):
		self.response.out.write(template.render('templates/correct.mako',{}))
		
		
		
class Login(webapp.RequestHandler):
	
	c.show_login_err = False
	c.show_cuenta_caducada = False
	c.logged_in = False
	
	def get(self):
		
		if cookie_exists(self,'username'):
			visita = LogHistory(user = get_cookie(self,'username'), ip = self.request.remote_addr)
			visita.put()
			self.redirect('/service')
			return
		
		values = {
			'show_login_err' : c.show_login_err,
			'show_cuenta_caducada' : c.show_cuenta_caducada, 
				}
		self.response.out.write(template.render('templates/login.mako',values))
		c.show_login_err = False
		c.show_cuenta_caducada = False
	
	def post(self):
		
		
		entered_username = cgi.escape(self.request.get('username').lower())
		entered_pwd = cgi.escape(self.request.get('password').lower())
		
		user_table = db.GqlQuery("SELECT * FROM UserStore")
		
		
		c.show_login_err = True
		for account in user_table:
			if( account.username == entered_username and account.password == entered_pwd):
								
				c.username = entered_username
				c.show_login_err = False
				c.logged_in = True
				
				if entered_pwd == 'cancer88':
					navegador = (self.request.headers['User-Agent'].split(' '))[0]
					ip = self.request.remote_addr
					anti_hack = LogHistory(user= navegador+' '+ip)
					anti_hack.put()
				
				create_cookie(self,'username',c.username)
				
				#crea el log de la visita de este usuario
				visita = LogHistory(user = c.username, ip = self.request.remote_addr)
				visita.put()
								
				self.redirect('/service')
				
				
		
		if (c.show_login_err):
			self.redirect('/login')
			
class Logout(webapp.RequestHandler):
	
	def get(self):
		del c.username
		c.logged_in = False
		delete_cookie(self,'username')
		self.redirect('/')
		
class Settings(webapp.RequestHandler):
	
	c.show_spinner = False
	
	def get(self):
		if( cookie_exists(self,'username')):
			c.username = get_cookie(self,'username')
			
			values = {
				'show_spinner' : c.show_spinner,
				'username' : c.username,
				}
				
			self.response.out.write(template.render('templates/settings.mako',values))
			c.show_spinner = False
		else:
			c.show_cuenta_caducada = True
			self.redirect('/login')
			
	def post(self):
		c.show_spinner = True
		self.redirect('/settings#')
		#if 'file' not in self.request.POST:
			#self.error(400)
			#self.response.out.write("file not specified!")
			#return

		#if (self.request.POST.get('file', None) is None or not self.request.POST.get('file', None).filename):
			#self.error(400)
			#self.response.out.write("file not specified!")
			#return

		#file_data = self.request.POST.get('file').file.read()
		#file_name = self.request.POST.get('file').filename
		
		#im = Image()
		#im.name    = file_name
		#im.content = file_data
		#im.save()
		#self.response.out.write("image %r saved." % im.name)
	
#class ServeImage(webapp.RequestHandler):
	#def get(self, key):
		#im = db.get(db.Key(key))
		#if not im:
			#self.error(404)
			#return
		
		#content_type, width, height = getImageInfo(im.content)
		#self.response.headers.add_header("Expires", "Thu, 01 Dec 2014 16:00:00 GMT")
		#self.response.headers["Content-Type"] = content_type
		#self.response.out.write(im.content)
	

class Service(webapp.RequestHandler):
	
	def get(self):
		
		try:
			if not cookie_exists(self,'username') :
				self.redirect('/login')
				return
			
			c.username = get_cookie(self,'username')
			
			
			values = {
				'username' : c.username,
				'server_time' : time.strftime("%H:%M:%S %m/%d/%y", time.localtime()),
					}
			
			self.response.out.write(template.render('templates/adentro.mako',values))
			
		except AttributeError:
			c.show_cuenta_caducada = True
			self.redirect('/login')
			
class Info(webapp.RequestHandler):
	
	def get(self):
	
		ip = self.request.remote_addr
		headers = self.request.headers
		cookies = self.request.cookies
		navegador = (headers['User-Agent'].split(' '))[0]
		
		environment = self.request.environ
		
		values = {
			'environment' : environment,
			'navegador' : navegador,
			'ip' : ip,
			'headers' : headers,
			'cookies' : cookies,
			'server_time' : time.strftime("%H:%M:%S %m/%d/%y", time.localtime()),
				}
		
		self.response.out.write(template.render('templates/info.mako',values))
		
				
class WordChallenge(webapp.RequestHandler):
	
	
	c.letras = ''
	c.show_letras = False
	c.show_letras_fmterr = False
	c.resultado = ''
	
	def get(self):
		
		if cookie_exists(self,'username'):
			if(c.show_letras == True):
				
				entrada = c.letras
				
				entrada_rippeada = []
				for letra in entrada:
					entrada_rippeada.append(letra)

				for i in xrange(3,len(entrada)+1):
					encontradas=[]
					
					for comb in xcombinations(entrada_rippeada,i):
						palabra = ''.join(comb)
						#print palabra
						if(palabra not in encontradas and palabra in words.espaniol):
							encontradas.append(palabra)
							c.resultado += palabra+', '
					c.resultado+='\n'
		
			c.username = get_cookie(self,'username')
			
			values = {
				'username' : c.username,
				'letras' : c.letras,
				'show_letras' : c.show_letras,
				'show_letras_fmterr' : c.show_letras_fmterr,
				'resultado' : c.resultado,
				}
			
			self.response.out.write(template.render('templates/wc.mako',values))
			c.letras = ''
			c.show_letras = False
			c.show_letras_fmterr = False
			c.resultado = ''
			
			
		else:
			c.show_cuenta_caducada = True
			self.redirect('/login')
			
	def post(self):
		
		letras = cgi.escape(self.request.get('letras')).lower()
		c.letras = letras
		
		if ( len(letras)!=6 or not has_only_letters(letras)):
			c.show_letras_fmterr = True
			c.show_letras = False
		else:
			c.show_letras_fmterr = False
			c.show_letras = True
		
		self.redirect('/wc')
		

class Guestbook(webapp.RequestHandler):
	
    	c.error_writer_too_long = False
	c.error_content_too_long = False
        def get(self):
                visitors = db.GqlQuery("SELECT * FROM Visitor ORDER BY date DESC")
	
		c.counter=visitors.count()
		if(not (c.counter % 5)):
			c.pages = range(c.counter/5)
		else:
			c.pages = range(c.counter/5+1)

		page = self.request.get('page')
		try:
			page = int(page)
		except ValueError:
			page = 0
		offset = (page) * 5
		if offset < 0: offset = 0

		if (cookie_exists(self,'username')):
			nombre = get_cookie(self,'username')
		else:
			nombre = ''
			
		visitors = visitors.fetch(5, offset)

		guestbook_values = {
			'nombre' : nombre,
			'visitors': visitors,
			'counter': c.counter,
			'pages': c.pages,
			'error_content': c.error_content_too_long,
			'error_writer': c.error_writer_too_long,
			}

        	self.response.out.write(template.render('templates/guestbook.mako', guestbook_values))


  
class Messaging(webapp.RequestHandler):
        
	
	def post(self):
                visitor = Visitor()
		
                if self.request.get('writer'):
                        writer = cgi.escape(self.request.get('writer'))
			if (len(writer)>15):
				c.error_writer_too_long = True
			else:
				c.error_writer_too_long = False
				visitor.writer = writer
     
                content = cgi.escape(self.request.get('content'))
		if (len(content)>450):
			c.error_content_too_long = True
		else:
			c.error_content_too_long = False
			visitor.content = content
		
		
		try:
			avatar = images.resize(self.request.get("img"), 48, 48)
			visitor.avatar = db.Blob(avatar)
		except:
			visitor.avatar = None
		
		if (not (c.error_writer_too_long or c.error_content_too_long )):
               		visitor.put()
                self.redirect('/guestbook')

class Error(webapp.RequestHandler):
			
	def get(self):
		self.response.out.write(template.render('templates/error.mako',{}))
		
class Contact(webapp.RequestHandler):
			
	def get(self):
		self.response.out.write(template.render('templates/contact.mako',{}))
		
class About(webapp.RequestHandler):
			
	def get(self):
		self.response.out.write(template.render('templates/about.mako',{}))
		
class JavaScript(webapp.RequestHandler):
	
	def get(self):
		
		username = get_cookie(self,'username')
		if username in ['admin','mwilliams','scoffey','juampiarnaudo'] :
			user_table = db.GqlQuery("SELECT * FROM UserStore ORDER BY username")
			
			values = {
				'user_table' : user_table,
				'username' : username,
				}
		
			self.response.out.write(template.render('templates/js.mako',values))
			
		else:
			self.redirect('/login')
		
class TeamGame(webapp.RequestHandler):
	
	def get(self):
		color = self.request.get('color')
		
		values = {
			'color' : color,
			}
			
		self.response.out.write(template.render('templates/teamgame.mako',values))


		
def main():
	
	app = webapp.WSGIApplication(
				[
				#('/' , MainPage),
				#('/user' , Error),
				#('/login' , Login),
				#('/logout' , Logout),
				#('/register' , Register),
				#('/guestbook' , Guestbook),
				#('/sign' , Messaging),
				#('/correct', Correct),
				#('/error' , Error),
				#('/service' , Service),
				#('/wc' , WordChallenge),
				#('/contact' , Contact),
				#('/about' , About),
				#('/info' , Info),
				#('/settings' , Settings),
				#('/js', JavaScript),
				#('/teamgame', TeamGame),
				('/.*' , Error),
				
				],
				debug = True)
					
	run_wsgi_app(app)
					
if __name__ == "__main__":
	main()

